﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Globalization;
using System.Threading;

namespace Mytrip.Localization
{
    public class LocalizationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //Задаем культуру по умолчанию
            string culture = LocalisationSetting.defaultCulture;
            //Берем культуру из сессии
            if (filterContext.HttpContext.Session["culture"] != null)
                culture = filterContext.HttpContext.Session["culture"].ToString();
            //Берем культуру из браузера
            if (filterContext.HttpContext.Request.UserLanguages[0] != null)
                culture = filterContext.HttpContext.Request.UserLanguages[0];
            //Берем культуру из куки
            if (filterContext.HttpContext.Request.Cookies["myTripCulture"] != null)
                culture = filterContext.HttpContext.Request.Cookies["myTripCulture"].Value;
            //Проверяем на культуры сайта
            if (LocalisationSetting.allCulture.IndexOf(culture) == -1)
                culture = LocalisationSetting.defaultCulture;
            //Задаем культуру по умолчанию
            if (!LocalisationSetting.unlockAllCulture)
                culture = LocalisationSetting.defaultCulture;
            /* HttpCookie myCookie = new HttpCookie("myTripCulture", culture);
             myCookie.Expires = DateTime.Now.AddMonths(12);
             if (HttpContext.Current.Response.Cookies["myCookie"] == null)
                 HttpContext.Current.Response.Cookies.Add(myCookie);
             else
             {
                 HttpContext.Current.Response.Cookies.Remove("myCookie");
                 HttpContext.Current.Response.Cookies.Add(myCookie);
             }*/
            CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(culture);
            filterContext.HttpContext.Session["culture"] = cultureInfo.Name;
            Thread.CurrentThread.CurrentCulture = cultureInfo;
            Thread.CurrentThread.CurrentUICulture = cultureInfo;
        }
    }
}
